package core;

import java.awt.AWTException;
import java.awt.Robot;
import java.awt.event.KeyEvent;

import javax.swing.JTable;

public class KeyInputProcessor {
	private static KeyInputProcessor instance = null;
	private long lastAdded;
	StringBuilder input;
	long delay = 3000; // delay after which input is wasted

	public static KeyInputProcessor getInstance() {
		if (instance == null) {
			instance = new KeyInputProcessor();
		}
		return instance;
	}

	private KeyInputProcessor() {
		this.input = new StringBuilder();
	}

	public void processInput(KeyEvent event) {
		if (("" + event.getKeyChar()).matches(Constants.VALID_CHARS_REGEX)) {

			JTable source = (JTable) event.getSource();
			String toSearch = this.add(event.getKeyChar()).toLowerCase();
			int column = source.getSelectedColumn();

			int startRow = source.getSelectedRow();
			boolean yetNotFound = true;

			for (int i = startRow; i < source.getRowCount(); i++) {
				String cellValue = source.getValueAt(i, column).toString().toLowerCase();
				if (cellValue.matches(toSearch + ".*")) {
					yetNotFound = false;
					source.setRowSelectionInterval(i, i);
					source.setColumnSelectionInterval(column, column);
					break;
				}
			}
			if (yetNotFound) {
				for (int i = 0; i < startRow; i++) {
					String cellValue = source.getValueAt(i, column).toString().toLowerCase();
					if (cellValue.matches(toSearch + ".*")) {
						source.setRowSelectionInterval(i, i);
						source.setColumnSelectionInterval(column, column);
						break;
					}
				}
			}
			try {
				Robot robot = new Robot();
				robot.keyPress(38); // up arrow
				robot.keyRelease(38); // up arrow
				robot.keyPress(40); // down arrow
				robot.keyRelease(40); // down arrow

			} catch (AWTException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
	}

	private String add(char keyChar) {
		if (("" + keyChar).matches("[A-Z|a-z]")) {

			if (this.input.length() == 0) {
				this.lastAdded = System.currentTimeMillis();
				this.input.append(keyChar);
			}

			else {
				if ((System.currentTimeMillis() - this.lastAdded) > this.delay) {
					this.input = new StringBuilder();
				}
				this.lastAdded = System.currentTimeMillis();
				this.input.append(keyChar);
			}

			return this.input.toString();
		} else {
			return "";
		}
	}
}
